/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

/**
 * @param {string | number} time
 * @returns {string}
 */
export function formatTime(time: string | number | Date = "") {
  const timeObj = time ? new Date(time) : new Date();
  return `${timeObj.getFullYear()}-${
    timeObj.getMonth() + 1 < 10
      ? "0" + (timeObj.getMonth() + 1)
      : timeObj.getMonth() + 1
  }-${timeObj.getDate() < 10 ? "0" + timeObj.getDate() : timeObj.getDate()} ${
    timeObj.getHours() < 10 ? "0" + timeObj.getHours() : timeObj.getHours()
  }:${
    timeObj.getMinutes() < 10
      ? "0" + timeObj.getMinutes()
      : timeObj.getMinutes()
  }:${
    timeObj.getSeconds() < 10
      ? "0" + timeObj.getSeconds()
      : timeObj.getSeconds()
  }`;
}

// 计算两个日期相差的天数
export function getDaysDifference(
  date1: Date | string,
  date2: Date | string
): number {
  // 将日期字符串转换为Date对象
  const d1 = new Date(date1);
  const d2 = new Date(date2);

  // 计算相差的毫秒数
  const diffInMilliseconds = d2.getTime() - d1.getTime();

  // 将毫秒数转换为天数
  const millisecondsPerDay = 24 * 60 * 60 * 1000;
  const diffInDays = Math.floor(diffInMilliseconds / millisecondsPerDay);

  return diffInDays;
}
/* 是否是手机 */
export const isMobile = () => {
  let reg =
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i;
  let flag = reg.test(window.navigator.userAgent);
  return flag;
};

export const isHttps = () => {
  return window.location.protocol === "https:";
};
